package com.chookss.home.audit.clockIn;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.entity.ClockInDetailEntity;
import com.chookss.home.entity.ClockInGroupEntity;
import com.chookss.home.entity.ClockInRecordEntity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.DrawableTextView;
import com.google.gson.reflect.TypeToken;
import com.lvgroup.hospital.base.BaseAct;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ClockInReissueCardActivity extends BaseAct {
    //补卡
    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.tvSure)
    TextView tvSure;
    @BindView(R.id.tvTime)
    DrawableTextView tvTime;
    @BindView(R.id.tvStatus)
    DrawableTextView tvStatus;
    @BindView(R.id.tvGroup)
    DrawableTextView tvGroup;
    @BindView(R.id.edContent)
    EditText edContent;

    private ClockInRecordEntity clockInRecordEntity = null;
    private int type = 1;//1上班卡0下班卡
    private String ruleStartTime, ruleEndTime;//考勤规则下的上班时间及下班时间
    private int hour, minute;//自己选择的 时分
    private List<ClockInGroupEntity> groupEntities = new ArrayList<>();
    private String[] groupArray = null;
    private String groupCode = "";//选择的项目组和节日下标
    private int workflowType = 3;//3补卡5外勤
    private boolean edit = false;//默认是新增补卡信息，也可以修改 补卡和外勤（外勤和补卡流程被拒可以修改）
    private ClockInDetailEntity clockInDetailEntity;//修改 补卡和外勤所用实体类

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clock_in_reissue_card);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        edit = getIntent().getBooleanExtra("edit", false);
        if (edit) {
            //外勤和补卡的修改逻辑
            workflowType = getIntent().getIntExtra("workflowType", 3);
            type = getIntent().getIntExtra("type", 1);
            clockInDetailEntity = (ClockInDetailEntity) getIntent().getSerializableExtra("clockInDetailEntity");
            if (clockInDetailEntity != null) {
                if (workflowType == 3) {
                    commonTitleTxt.setText("补卡修改");
                    if (type == 1) {
                        if (!Utils.isNull(clockInDetailEntity.getBukaStartTime())) {
                            tvTime.setText(clockInDetailEntity.getBukaStartTime());
                            tvStatus.setText("上班补卡");
                            groupCode = clockInDetailEntity.getItemGroupCode();
                            if (!Utils.isNull(clockInDetailEntity.getItemGroupName())) {
                                tvGroup.setText(clockInDetailEntity.getItemGroupName() + "(" + ClockInUtils.getGroupEnd(clockInDetailEntity.getItemGroupCode()) + ")");
                            } else {
                                tvGroup.setText("");
                            }
                            if (!Utils.isNull(clockInDetailEntity.getShangbanBukaRemark())) {
                                edContent.setText(clockInDetailEntity.getShangbanBukaRemark());
                            } else {
                                edContent.setText("");
                            }
                        }
                    } else {
                        if (!Utils.isNull(clockInDetailEntity.getBukaEndTime())) {
                            tvTime.setText(clockInDetailEntity.getBukaEndTime());
                            tvStatus.setText("下班补卡");
                            groupCode = clockInDetailEntity.getXiabanItemGroupCode();
                            if (!Utils.isNull(clockInDetailEntity.getXiabanItemGroupName())) {
                                tvGroup.setText(clockInDetailEntity.getXiabanItemGroupName() + "(" + ClockInUtils.getGroupEnd(clockInDetailEntity.getXiabanItemGroupCode()) + ")");
                            } else {
                                tvGroup.setText("");
                            }
                            if (!Utils.isNull(clockInDetailEntity.getXiabanBukaRemark())) {
                                edContent.setText(clockInDetailEntity.getXiabanBukaRemark());
                            } else {
                                edContent.setText("");
                            }
                        }
                    }
                } else {
                    commonTitleTxt.setText("外勤修改");
                    if (type == 1) {
                        if (!Utils.isNull(clockInDetailEntity.getStartTime())) {
                            tvTime.setText(clockInDetailEntity.getStartTime());
                            tvStatus.setText("上班外勤打卡");
                            groupCode = clockInDetailEntity.getItemGroupCode();
                            if (!Utils.isNull(clockInDetailEntity.getItemGroupName())) {
                                tvGroup.setText(clockInDetailEntity.getItemGroupName() + "(" + ClockInUtils.getGroupEnd(clockInDetailEntity.getItemGroupCode()) + ")");
                            } else {
                                tvGroup.setText("");
                            }
                            if (!Utils.isNull(clockInDetailEntity.getShangbanWaiqinRemark())) {
                                edContent.setText(clockInDetailEntity.getShangbanWaiqinRemark());
                            } else {
                                edContent.setText("");
                            }
                        }
                    } else {
                        if (!Utils.isNull(clockInDetailEntity.getEndTime())) {
                            tvTime.setText(clockInDetailEntity.getEndTime());
                            tvStatus.setText("下班外勤打卡");
                            groupCode = clockInDetailEntity.getXiabanItemGroupCode();
                            if (!Utils.isNull(clockInDetailEntity.getXiabanItemGroupName())) {
                                tvGroup.setText(clockInDetailEntity.getXiabanItemGroupName() + "(" + ClockInUtils.getGroupEnd(clockInDetailEntity.getXiabanItemGroupCode()) + ")");
                            } else {
                                tvGroup.setText("");
                            }
                            if (!Utils.isNull(clockInDetailEntity.getXiabanWaiqinRemark())) {
                                edContent.setText(clockInDetailEntity.getXiabanWaiqinRemark());
                            } else {
                                edContent.setText("");
                            }
                        }
                    }


                }
            }
        } else {
            commonTitleTxt.setText("补卡申请");
            clockInRecordEntity = (ClockInRecordEntity) getIntent().getSerializableExtra("data");
            type = getIntent().getIntExtra("type", 1);
            if (clockInRecordEntity != null) {
                if(Utils.isNull(clockInRecordEntity.getRuleStartTime())){
                    ruleStartTime ="09:00";
                }else{
                    ruleStartTime = clockInRecordEntity.getRuleStartTime();
                }
                if(Utils.isNull(clockInRecordEntity.getRuleEndTime())){
                    ruleEndTime ="18:00";
                }else{
                    ruleEndTime = clockInRecordEntity.getRuleEndTime();
                }
                if (1 == type) {
                    tvTime.setText(clockInRecordEntity.getStatisDate() + " " + ruleStartTime);
                    if (Utils.isNull(ruleStartTime)) {
                        hour = 9;
                        minute = 0;
                    } else {
                        String[] times = ruleStartTime.split(":");
                        if (times.length > 1) {
                            hour = ClockInUtils.getTimeInt(times[0]);
                            minute = ClockInUtils.getTimeInt(times[1]);
                        } else {
                            hour = 9;
                            minute = 0;
                        }
                    }
//                    1-正常 2-迟到 3-旷工 4-早退 5-补卡6请假
                    if("2".equals(clockInRecordEntity.getShangbanDakaType())||"3".equals(clockInRecordEntity.getShangbanDakaType())||"4".equals(clockInRecordEntity.getShangbanDakaType())){
                        tvStatus.setText("上班补卡");
                    }else{
                        tvStatus.setText("上班未打卡");
                    }

                } else {
                    tvTime.setText(clockInRecordEntity.getStatisDate() + " " + ruleEndTime);
                    if (Utils.isNull(ruleEndTime)) {
                        hour = 18;
                        minute = 0;
                    } else {
                        String[] times = ruleEndTime.split(":");
                        if (times.length > 1) {
                            hour = ClockInUtils.getTimeInt(times[0]);
                            minute = ClockInUtils.getTimeInt(times[1]);
                        } else {
                            hour = 18;
                            minute = 0;
                        }
                    }
                    if("2".equals(clockInRecordEntity.getXiabanDakaType())||"3".equals(clockInRecordEntity.getXiabanDakaType())||"4".equals(clockInRecordEntity.getXiabanDakaType())){
                        tvStatus.setText("下班补卡");
                    }else{
                        tvStatus.setText("下班未打卡");
                    }
                }
            }
        }
        getGroupList();
    }

    private void getGroupList() {
        //项目组基本数据
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<ClockInGroupEntity>>>() {
        }.getType(), null, Urls.selectMyItemGroupList, SignUtils2.makeSignStr(null), false, new ObserverCallback<List<ClockInGroupEntity>>() {
            @Override
            public void onSuccess(List<ClockInGroupEntity> data) {
                if (data != null && data.size() > 0) {
                    if (tvTime == null) {
                        return;
                    }
                    groupEntities.addAll(data);
                    groupArray = new String[groupEntities.size()];
                    for (int i = 0; i < groupEntities.size(); i++) {
                        if("1".equals(groupEntities.get(i).getMainCd())){
                            groupArray[i] = groupEntities.get(i).getGroupName()+"[常驻]";
                        }else{
                            groupArray[i] = groupEntities.get(i).getGroupName();
                        }
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void upload() {
        if (groupEntities.size() == 0) {
            MyToast.show("无可选项目组，请联系管理员配置");
            return;
        }
        if (Utils.isNull(groupCode)) {
            MyToast.show("请先选择项目组");
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("itemGroupCode", groupCode);
        map.put("shangbanCd", type + "");
        String url = "";
        if (edit) {
            if (clockInDetailEntity == null) {
                MyToast.show("网络异常，请稍后重试");
                return;
            }
            url = Urls.updateDakaInfo;
            String time=tvTime.getText().toString();
            if(!Utils.isNull(time)){
              if(time.length()==16){
                  time=time+":00";
              }
            }
            if (workflowType == 3) {
                if (1 == type) {
                    //上班卡
                    map.put("bukaStartTime",time);
                    map.put("shangbanBukaRemark", edContent.getText().toString());
                    map.put("shangbanDakaType", clockInDetailEntity.getShangbanDakaType());
                } else {
                    map.put("bukaEndTime", time);
                    map.put("xiabanBukaRemark", edContent.getText().toString());
                    map.put("xiabanDakaType", clockInDetailEntity.getXiabanDakaType());
                }
            } else {
                if (1 == type) {
                    //上班卡
                    map.put("startTime", time);
                    map.put("shangbanWaiqinRemark", edContent.getText().toString());
                } else {
                    map.put("endTime", time);
                    map.put("xiabanWaiqinRemark", edContent.getText().toString());
                }
            }
            if (!Utils.isNull(clockInDetailEntity.getProjectCode())) {
                map.put("projectCode", clockInDetailEntity.getProjectCode());
            }
            if (!Utils.isNull(clockInDetailEntity.getWorkflowId())) {
                map.put("workflowId", clockInDetailEntity.getWorkflowId());
            }
        } else {
            if (clockInRecordEntity == null) {
                MyToast.show("网络异常，请稍后重试");
                return;
            }
            url = Urls.insertBukaInfo;
            if (1 == type) {
                //上班卡
                map.put("bukaStartTime", tvTime.getText().toString() + ":00");
                map.put("shangbanBukaRemark", edContent.getText().toString());
                map.put("shangbanDakaType", clockInRecordEntity.getShangbanDakaType());
            } else {
                map.put("bukaEndTime", tvTime.getText().toString() + ":00");
                map.put("xiabanBukaRemark", edContent.getText().toString());
                map.put("xiabanDakaType", clockInRecordEntity.getXiabanDakaType());
            }
            if (!Utils.isNull(clockInRecordEntity.getId())) {
                map.put("id", clockInRecordEntity.getId());
            }
        }
        showLoading();
        MyHttpRequest.getDefault().postRequestCompat(this, url, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String s) throws Exception {
                dismissLoading();
                try {
                    JSONObject reObject = new JSONObject(s);
                    if ("200".equals(reObject.getString("code"))) {
                        EventBus.getDefault().post(new MyEvent("RefreshClockInRecord"));
                        MyToast.show("提交成功");
                        finish();
                    } else {
                        MyToast.show(reObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("提交失败，请稍后重试");
                }
            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    @OnClick({R.id.common_title_back, R.id.tvSure, R.id.tvGroup})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.tvSure:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (Utils.isNull(edContent.getText().toString())) {
                    MyToast.show("请输入说明");
                    return;
                }
                upload();
                break;
            case R.id.tvGroup:
                if (groupArray == null) {
                    return;
                }
                if (groupEntities.size() == 0) {
                    MyToast.show("项目组为空，请联系管理员后重试");
                    return;
                }
                new XPopup.Builder(ClockInReissueCardActivity.this)
                        .maxWidth(Utils.dip2px(ClockInReissueCardActivity.this, 260))
                        .maxHeight(Utils.dip2px(ClockInReissueCardActivity.this, 300))
                        .asCenterList("请选择项目组", groupArray,
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        groupCode = groupEntities.get(position).getGroupCode();
                                        tvGroup.setText(text.replace("[常驻]","") + "(" + ClockInUtils.getGroupEnd(groupEntities.get(position).getGroupCode()) + ")");
                                    }
                                })
                        .show();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(edContent!=null){
            Utils.hideInputKeyboard(this,edContent);
        }
    }
}
